package cn.jdy.plugins.admin;

import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.service.UserRoleService;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.EncodeUtil;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.admin.export.EvaluationCsiveExcelView;
import cn.jdy.plugins.admin.export.EvaluationSfiveExcelView;
import cn.jdy.plugins.admin.export.EvaluationXbliveExcelView;
import cn.jdy.plugins.entity.EvaluationProject;
import cn.jdy.plugins.entity.ExamOptions;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.entity.Live;
import cn.jdy.plugins.entity.LiveDate;
import cn.jdy.plugins.entity.LiveTimeFrame;
import cn.jdy.plugins.service.AdvertisingService;
import cn.jdy.plugins.service.ChatService;
import cn.jdy.plugins.service.EvaluationProjectService;
import cn.jdy.plugins.service.ExamOptionsService;
import cn.jdy.plugins.service.ExamQuestionsService;
import cn.jdy.plugins.service.LabelService;
import cn.jdy.plugins.service.LineService;
import cn.jdy.plugins.service.LiveService;
import cn.jdy.plugins.service.PptImgService;
import cn.jdy.plugins.service.RedPacketReceiveService;
import cn.jdy.plugins.service.RelatedVideoService;
import cn.jdy.plugins.service.VisitLogService;








/**
 * @title 直播控制类
 * @author lutan
 */
@Controller
@RequestMapping("/countLive")
public class LiveCountCtrl extends BaseCtrl {
	@Autowired
	private LineService lineService;
	@Autowired
	private RelatedVideoService relatedVideoService;
	@Autowired
	private RedPacketReceiveService redPacketReceiveService;
	@Autowired
	private UserRoleService userRoleService;
	@Autowired
	private UserService userService;
	@Autowired
	private LiveService LiveService;
	@Autowired
	private ChatService chatService;
	@Autowired
	private ConfService confService;
	@Autowired
	private LabelService labelService;
	@Autowired
	private AdvertisingService advertisingService;
	@Autowired
	private VisitLogService visitLogService;
	@Autowired
	private PptImgService pptImgService;
	@Autowired
	protected HttpSession session;
	@Autowired
	private EvaluationProjectService evaluationProjectService;
	@Autowired
	private ExamOptionsService examOptionsService;
	@Autowired
	private ExamQuestionsService examQuestionsService;
	
	// 默认列表路径
	private static String viewName = "redirect:/live/list?s=";

	

	private Long id;
	private Long day;
	/**
	 * 获取当前直播的省份统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countSfLive")
	public ModelAndView countLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("data",obj);

		mv.setViewName("/countLive/countSfLive.jsp");
		return mv;
	}
	/**
	 * 异步查询统计这个直播省份综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountSfQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountSfQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		
				jsonMap.put("dataList", LiveService.liveSfCountQuery(live,fromDate, toDate));
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 导出省份综合记录
	 * @param evaluationRecord
	 * @param fromDate
	 * @param toDate
	 * @param model
	 * @return
	 */
	@RequestMapping("/exliveCountQueryByPage")
	public ModelAndView exliveCountQueryByPage(Live live,String fromDate, String toDate,ModelMap model) {
	    List<Map<String, Object>> list = LiveService.liveSfCountQuery(live,fromDate, toDate);
	    model.put("dataSet", list);
	    model.put("searchDate", fromDate+"-"+toDate);
	    EvaluationSfiveExcelView evaluationRecordExcelView = new EvaluationSfiveExcelView();
	  
	    return new ModelAndView(evaluationRecordExcelView, model);
	}
	
	
	/**
	 * 获取当前直播的城市统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countCsLive")
	public ModelAndView countCsLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		
		mv.addObject("data",obj);

		mv.setViewName("/countLive/countCsLive.jsp");
		return mv;
	}
	/**
	 * 异步查询统计这个直播访问综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountCsQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountCsQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
		
				jsonMap.put("dataList", LiveService.liveCsCountQuery(live,fromDate, toDate));
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 导出统计综合记录
	 * @param evaluationRecord
	 * @param fromDate
	 * @param toDate
	 * @param model
	 * @return
	 */
	@RequestMapping("/exscliveCountQueryByPage")
	public ModelAndView exscliveCountQueryByPage(Live live,String fromDate, String toDate,ModelMap model) {
	    List<Map<String, Object>> list = LiveService.liveCsCountQuery(live,fromDate, toDate);
	    model.put("dataSet", list);
	    model.put("searchDate", fromDate+"-"+toDate);
	    EvaluationCsiveExcelView evaluationRecordExcelView = new EvaluationCsiveExcelView();
	  
	    return new ModelAndView(evaluationRecordExcelView, model);
	}

	/**
	 * 获取当前直播的性别统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countXbLive")
	public ModelAndView countXbLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("data",obj);
		mv.setViewName("/countLive/countXbLive.jsp");
		return mv;
	}
	/**
	 * 异步查询统计这个直播省份综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountXbQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountXbQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
				jsonMap.put("dataList", LiveService.liveXbCountQuery(live,fromDate, toDate));
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);

		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 导出性别综合记录
	 * @param evaluationRecord
	 * @param fromDate
	 * @param toDate
	 * @param model
	 * @return
	 */
	@RequestMapping("/exxbliveCountQueryByPage")
	public ModelAndView exxbliveCountQueryByPage(Live live,String fromDate, String toDate,ModelMap model) {
	    List<Map<String, Object>> list = LiveService.liveXbCountQuery(live, fromDate, toDate);
	    model.put("dataSet", list);
	    model.put("searchDate", fromDate+"-"+toDate);
	    EvaluationXbliveExcelView evaluationRecordExcelView = new EvaluationXbliveExcelView();
	  
	    return new ModelAndView(evaluationRecordExcelView, model);
	}
	
	/**
	 * 获取当前直播的性别统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countSjLive")
	public ModelAndView countSjLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("data",obj);
		mv.setViewName("/countLive/countSjLive.jsp");
		return mv;
	}
	/**
	 * 异步查询统计这个直播省份综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountSjQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountSjQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			id=live.getId();
			List<LiveDate> list = new ArrayList<LiveDate>();
			String date1=LiveService.findOne("id",live.getId()).getFromDate();
			String date=LiveService.findOne("id",live.getId()).getToDate();
			String stra = date1.toString().split(" ")[0];//年月日
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = df.parse(date);
			Date d2 = df.parse(date1);
			long diff = d1.getTime() - d2.getTime();
			long days = diff / (1000 * 60 * 60 * 24)+1;//天数
			day=days;
			if(days>10){
				for (int i = 0; i < 10; i++) {
					LiveDate liveDate =new LiveDate();
					liveDate.setSj(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("aa")));
					liveDate.setCs(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("bb")));
					liveDate.setRs(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("cc")));
					list.add(liveDate);
				}
			}else{
				for (int i = 0; i < days; i++) {
					LiveDate liveDate =new LiveDate();
					liveDate.setSj(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("aa")));
					liveDate.setCs(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("bb")));
					liveDate.setRs(String.valueOf(LiveService.liveSjCountQuery(live,stra, toDate,i).get("cc")));
					list.add(liveDate);
				}
			}
				
			 	jsonMap.put("dataList", list);
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	@RequestMapping("/exsjliveCountQueryByPage")
	public void exportExcel(HttpServletResponse response,HttpServletRequest request){	
		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFSheet sheet = workBook.createSheet("时间");
	    HSSFRow rowTitle = sheet.createRow(0);
		rowTitle.createCell((int) 0).setCellValue("时间段");
		rowTitle.createCell((int) 1).setCellValue("页面访问次数");
		rowTitle.createCell((int) 2).setCellValue("页面访问人数");
		Live live=new Live();
		String date1=LiveService.findOne("id",id).getFromDate();
		String stra = date1.toString().split(" ")[0];//年月日
		live.setId(id);
		for (int i = 0; i <= day+1; i++) {
			HSSFRow row = sheet.createRow(i+1);
			row.createCell((int) 0).setCellValue(String.valueOf(LiveService.liveSjCountQuery(live,stra, null,i).get("aa")));
			row.createCell((int) 1).setCellValue(Integer.valueOf(String.valueOf(LiveService.liveSjCountQuery(live,stra, null,i).get("bb"))));
			row.createCell((int) 2).setCellValue(Integer.valueOf(String.valueOf(LiveService.liveSjCountQuery(live,stra, null,i).get("cc"))));
		}	 
	    String fileName = "时间统计";
	    fileName = EncodeUtil.processFileName(request, fileName); 
		response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			workBook.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取当前直播的性别统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countSdLive")
	public ModelAndView countSdLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("data",obj);
		mv.setViewName("/countLive/countSdLive.jsp");
		return mv;
	}
	
	/**
	 * 异步查询统计这个直播省份综合信息
	 * 
	 * @param Live
	 * @return
	 */
	@RequestMapping("/liveCountSdQueryByPage")
	@ResponseBody
	public Map<String, Object> liveCountSdQueryByPage(Live live,String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			id=live.getId();
			List<LiveTimeFrame> list = new ArrayList<LiveTimeFrame>();
			String date1=LiveService.findOne("id",live.getId()).getFromDate();
			String date=LiveService.findOne("id",live.getId()).getToDate();
			String stra = date1.toString().split(" ")[0]+" 00:00:00";//年月日
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = df.parse(date);
			Date d2 = df.parse(date1);
			long diff = d1.getTime() - d2.getTime();
			long days = diff / (1000 * 60 * 60 * 24);//天数
			day=days;
			for (int i = 0; i <24; i++) {
				int x=i+1;
					LiveTimeFrame liveTimeFrame =new LiveTimeFrame();
					liveTimeFrame.setSd(String.valueOf(LiveService.liveSdCountQuery(live,stra, toDate,x,i).get("aa")+"~"+String.valueOf(LiveService.liveSdCountQuery(live,stra, toDate,x,i).get("bb"))));
					liveTimeFrame.setCs(String.valueOf(LiveService.liveSdCountQuery(live,stra, toDate,x,i).get("cc")));
					list.add(liveTimeFrame);
			}
			 	jsonMap.put("dataList", list);
				jsonMap.put("iTotalDisplayRecords", 1);
				jsonMap.put("iTotalRecords", 1);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	@RequestMapping("/exsdliveCountQueryByPage")
	public void exsdportExcel(HttpServletResponse response,HttpServletRequest request){	
		HSSFWorkbook workBook = new HSSFWorkbook();
		HSSFSheet sheet = workBook.createSheet("时段");
	    HSSFRow rowTitle = sheet.createRow(0);
		rowTitle.createCell((int) 0).setCellValue("时间段");
		rowTitle.createCell((int) 1).setCellValue("页面访问次数");
		Live live=new Live();
		String date1=LiveService.findOne("id",id).getFromDate();
		String stra = date1.toString().split(" ")[0]+" 00:00:00";//年月日
		live.setId(id);
		for (int i = 0; i < day*24; i++) {
			int x=i+1;
			HSSFRow row = sheet.createRow(i+1);
			row.createCell((int) 0).setCellValue(String.valueOf(LiveService.liveSdCountQuery(live,stra, null,x,i).get("aa")+"~"+String.valueOf(LiveService.liveSdCountQuery(live,stra, null,x,i).get("bb"))));
			row.createCell((int) 1).setCellValue(Integer.valueOf(String.valueOf(LiveService.liveSdCountQuery(live,stra, null,x,i).get("cc"))));
		}	 
	    String fileName = "时段统计";
	    fileName = EncodeUtil.processFileName(request, fileName); 
		response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
		OutputStream os = null;
		try {
			os = response.getOutputStream();
			workBook.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取当前直播的投票统计图表
	 * 
	 * @return
	 */
	@RequestMapping("/countTpLive")
	public ModelAndView countTpLive(Live obj) {
		ModelAndView mv = new ModelAndView();
		
		EvaluationProject  ep=evaluationProjectService.findOne("liveId",obj.getId()); //题头
		mv.addObject("ep", ep);// 题头
		if(ep!=null&&ep.getId()!=null){
			DetachedCriteria dc = DetachedCriteria.forClass(ExamQuestions.class);
		    dc.add(Restrictions.eq("projectId",ep.getId()));
			dc.addOrder(Order.asc("sort"));
			List<ExamQuestions> eqslist=examQuestionsService.find(dc);//题目
			for (int j = 0; j < eqslist.size(); j++) {
				ExamQuestions qe=eqslist.get(j);
				qe.setMplis(examQuestionsService.evaluationListRecord(Long.valueOf(qe.getId())));//选项
				
			}
			mv.addObject("eqslist", eqslist);
		}
		mv.addObject("data",obj);
		mv.setViewName("/countLive/countTpLive.jsp");
		return mv;
	}

}
